/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkEvent/MkEventPool.h"
#include "MkEvent.h"
#include "MkUtil/MkUtil.h"
#include "MkUtil/MkLog.h"

CMkEventPool::CMkEventPool()
    : m_bRun(FALSE)
{

}

Uint32 CMkEventPool::Start(Uint32 nCount/*=0*/)
{
    if (nCount == 0) {
        CMkUtil::GetSystemCpuThreadNum(nCount);
    }
    MkDebugLog("start event pool num:%d\n", nCount);
    Uint32 CurSize = m_VecEvent.size();

    for (Uint32 i = CurSize; i < nCount; i++) {
        CMkEvent *pEvent = new CMkEvent;
        if (!pEvent) {
            continue;
        }
        if (NoneError != pEvent->Start()) {
            delete pEvent;
            continue;
        }
        m_VecEvent.push_back(pEvent);
    }
    if (m_VecEvent.empty()) {
        return MallocFailed;
    }
    m_bRun = TRUE;
    return NoneError;
}

CMkEvent* CMkEventPool::GetFreeEvent()
{
    Uint32 MaxScore = 0;
    CMkEvent *FreeEvent = nullptr;
    MkVector<CMkEvent*>::iterator it = m_VecEvent.begin();
    for (; it != m_VecEvent.end(); it++) {
        if (MaxScore < (*it)->GetScore()) {
            FreeEvent = (*it);
            MaxScore = FreeEvent->GetScore();
        }
    }
    return FreeEvent;
}

Uint32 CMkEventPool::Stop()
{
    MkVector<CMkEvent*>::iterator it = m_VecEvent.begin();
    for (; it != m_VecEvent.end(); it++) {
        (*it)->Stop();
    }
    m_bRun = FALSE;
    return NoneError;
}

CMkEventPool::~CMkEventPool()
{
    MkVector<CMkEvent*>::iterator it = m_VecEvent.begin();
    for (; it != m_VecEvent.end(); it++) {
        MkDelete(*it);
    }
    m_VecEvent.clear();
}